<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/7/16
 * Time: 18:59
 */

namespace app\common\model;


use app\common\enum\StatusEnum;
use think\Exception;

class Role extends BaseModel
{
    protected $deleteTime = false;

    public function getRoleStatusTextAttr($value, $data) {
        $array = [10 => '无效', 20 => '禁用', 99 => '有效'];
        return $array[$data['roleStatus']];
    }

    /**
     * 创建或者编辑角色
     * @param $data
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateRole($data, $id = 0) {
        try {
            if ($id > 0) {
                $role = self::get($id);
                if (!$role) {
                    throw new Exception('角色不存在');
                }
                $check_auth = self::where('name', '=', $data['name'])
                    ->where('id', 'neq', $id)
                    ->find();
                if ($check_auth) {
                    throw new Exception('角色名称已存在');
                }
                $role->save($data);
            } else {
                $check_auth = self::where('name', '=', $data['name'])->find();
                if ($check_auth) {
                    throw new Exception('角色名称已存在');
                }

                self::create($data);
            }
            return return_data('保存成功！');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 获取管理员对应的权限
     * @param $roleIds
     * @return string
     */
    public static function getAdminAuthIds($roleIds) {
        $authIds = self::where('id', 'in', $roleIds)->where('status', '=', StatusEnum::ROLE_VALID)->column('auth_ids');
        return $authIds = implode($authIds, ',');
    }

    /**
     * 获取角色名称
     * @param $roleIds
     * @return string
     */
    public static function getNames($roleIds) {
        $authIds = self::where('id', 'in', $roleIds)->where('status', '=', StatusEnum::ROLE_VALID)->column('name');
        return $authIds = implode($authIds, ' , ');
    }
}